package com.example.segment_saver;
/*
 * Nov 16th 2012
 * Created By: Alex Drotar, Jacob Reiger 
 * Using code from: Ken Anderson 
 * Segment_Saver- This is meant to be run on Andriod mobile devices
 * 					The app will allow the user to take in a url that they
 * 					want to watch. If the user selects the update site button
 * 					The application will go and check if the site has changed 
 * 					since the last time the user looked at it.
 * 
 */
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

import android.util.Log;

public class SiteList  implements Iterable<String>{
	
	private Map<String,SiteData> sites;
	
	public SiteList()
	{
		sites= new TreeMap<String, SiteData>();
	}
	
	public int size()
	{
		return sites.size();
	}
	
	public void addSite(String name){
		sites.put(name, new SiteData());
	}
	
	public void addSite(String name , SiteData data)
	{
		sites.put(name, data);
	}
	
	public void clear()
	{
		sites.clear();
	}
	public boolean containsSite(String name){
		return sites.keySet().contains(name);
	}
	
	public void removeSite(String name){
		sites.remove(name);
	}
	
	public SiteData getSite(String name){
		return sites.get(name);
	}
	
	@Override
	public Iterator<String> iterator(){
		return sites.keySet().iterator();
	}
	
	public void save(File f)
	{
		try{
			ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(f));
			output.writeObject(sites);
			output.close();
			Log.i("Segment Saver", "Sites Saved to " +f +" "+ sites);
		}
		catch(FileNotFoundException ex)
		{
			Log.i("Segment Saver", "Error: File can not be Created");
		}
		catch(IOException ex){
			Log.i("Segment Saver", "Fatal ERROR while saving sites");
		}
	}
	@SuppressWarnings("unchecked") // This is for the TreeMap line.
	public void load(File f)
	{
		try{
			ObjectInputStream input = new ObjectInputStream( new FileInputStream(f));
			sites = (TreeMap<String, SiteData>) input.readObject();
			input.close();
			Log.i("Segment Saver", "Sites Loaded From "+f);
			Log.i("Segment_Saver", "Loaded: " +sites);
		}
		catch(FileNotFoundException ex){
			Log.i("Segment Saver", "File Not Found: "+f);
			sites.clear();
		}
		catch(IOException ex){
			Log.i("Segment Saver", "Fatal Error While Loading Sites.");
			sites.clear();
		}
		catch(ClassNotFoundException ex)
		{
			Log.i("Segment Saver", "Fatal Error While Loading Sites");
			sites.clear();
		}
	}

}
